package cn.b.sky.mes.em.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.b.sky.mes.em.dao.FailureDao;
import cn.b.sky.mes.em.model.Failure;
import cn.b.sky.mes.em.model.condition.FailureCondition;
import cn.b.sky.mes.em.service.FailureService;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;

/**
 * 
 * <strong>Title : FailureServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.mes.em.service.impl<br></strong>
 * <strong>Description : </strong>故障代码业务实现<br> 
 * <strong>Create on : 2015-11-3 下午02:03:55<br></strong>
 * <p>
 * @author zhaoxin01<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Service("failureService")
public class FailureServiceImpl implements FailureService {

  private static final Logger LOG = LoggerFactory.getLogger(FailureServiceImpl.class);

  @Resource
  FailureDao failureDao;

  @Override
  public List<Failure> selectFailureByCondition(FailureCondition failureCondition) {
    return failureDao.selectFailureByCondition(failureCondition);
  }

  @Override
  public int selectFailureCount(FailureCondition failureCondition) {
    return failureDao.selectFailureCount(failureCondition);
  }

  @Override
  public Failure selectFailureByCode(String siteCode, String failureCode) {
    return failureDao.selectFailureByCode(siteCode, failureCode);
  }

  @Override
  public void insertFailure(Failure failure) {
    failureDao.insertFailure(failure);

  }

  @Override
  public void updateFailure(Failure failure) {
    failureDao.updateFailure(failure);

  }

  @Override
  public BatchJobReport deleteFailure(String siteCode, String failureCode) {
    String cause = "";
    Boolean success = true;
    try {
      failureDao.deleteFailure(siteCode, failureCode);
    } catch (Exception e) {
      LOG.error("{}", e);
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        //外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(failureCode, cause, success);
  }

  @Override
  public List<Failure> selectFailureForSuggest(FailureCondition failureCondition) {
    return failureDao.selectFailureForSuggest(failureCondition);
  }

}
